package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.HttpClientUtils;
import com.example.dao.BaseInfo;
import com.example.dao.Client;
import com.example.entity.BasicInfo;
import com.example.entity.DetailInfo;
import com.example.mapper.InfoMapper;
import com.example.service.InfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.http.HttpEntity;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class InfoServiceImpl implements InfoService {
    public static SimpleDateFormat sdfS = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private InfoMapper infoMapper;
    @Override
    public PageInfo<BasicInfo> selectPickingCartonDetails(Integer pageNum, Integer pageSize, String name, String field,String startDate,String endDate,String comPartyId) {
        // 开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<BasicInfo> basicInfos = infoMapper.selectPickingCartonDetails(name, field, startDate, endDate,comPartyId);
        return PageInfo.of(basicInfos);
    }

    @Override
    public PageInfo<DetailInfo> getDetailInfo(String delvBchno, Integer pageNum, Integer pageSize, String name,String comPartyId) {
        // 开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        System.out.println("request.getName()2112======"+name);
        List<DetailInfo> detailInfos = infoMapper.getDetailInfo(delvBchno,name,comPartyId);
        return PageInfo.of(detailInfos);
    }

    @Override
    public Object delById(Map companyInfo, BasicInfo info, String key) {
        BaseInfo baseInfo = new BaseInfo();
        if ("1".equals(key)) {
            baseInfo.setInfno("3563");
        } else {
            baseInfo.setInfno("3562");
        }
        baseInfo.setMsgid("");
        baseInfo.setInsuplc_admdvs("null");
        baseInfo.setMdtrtarea_admvs("430199");
        baseInfo.setRecer_sys_code("20538");
        baseInfo.setDev_no("null");
        baseInfo.setDev_safe_info("null");
        baseInfo.setCainfo("null");
        baseInfo.setSigntype("SM3");
        baseInfo.setInfver("1.0.0");
        baseInfo.setOpter_type("1");
        baseInfo.setOpter("sphyy");

        String name = (String) companyInfo.get("name");
        baseInfo.setOpter_name(name);
        baseInfo.setInf_time(sdfS.format(new Date()));
        baseInfo.setFixmedins_code(info.getFixmedinsHilistId());
        baseInfo.setFixmedins_name(info.getFixmedinsHilistName());
        baseInfo.setSign_no("1088137");

        Map input = new HashMap();
        Map data = new HashMap();
        data.put("query_type", "file");
        data.put("delv_bchno", info.getdelvBchno());
        data.put("bchnoinfo", "");
        data.put("fixmedins_code", info.getFixmedinsHilistId());
        data.put("fixmedins_name", info.getFixmedinsHilistName());
        data.put("delventp_uscc", companyInfo.get("code"));
        data.put("delventp_name", companyInfo.get("name"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        String endDateStr = info.getEndDate();
        String startDateStr = info.getStartDate();
        if (endDateStr != null && !endDateStr.isEmpty() && !startDateStr.isEmpty()&& startDateStr != null) {
            data.put("opt_begntime", info.getStartDate());
            LocalDate end = LocalDate.parse(endDateStr, formatter);
            LocalDate endPlusOne = end.plusDays(1);
            data.put("opt_endtime", endPlusOne.format(formatter));
        }
        input.put("data", data);
        baseInfo.setInput(input);

        Map result = (Map) pushDxm(baseInfo, (String) companyInfo.get("ak"), (String) companyInfo.get("sk"), key);
        System.out.println("result======>"+result);
        String msg = (String) result.get("warn_msg");

        if ("1".equals(key)) {
            if (result.get("fileBytes") != null || result.get("file") != null) {
                // 返回 base64 内容和文件名给上层
                Map<String, Object> fileResult = new HashMap<>();
                fileResult.put("file", result.get("fileBytes")); // base64 或 byte[]
                fileResult.put("filename", result.get("filename")); // 下载文件名
                System.out.println("fileResult==========>"+fileResult);
                return fileResult;
            } else {
                throw new RuntimeException("下载失败：" + msg);
            }
        } else {
            // 原有删除流程
            if ("成功".equals(msg)) {
                 int updated = infoMapper.delById(companyInfo, info);
                System.out.println("删除成功");
            }
            return 0;
        }
    }


    @Override
    public PageInfo<BasicInfo> getResend(Integer pageNum, Integer pageSize, String name,String comPartyId) {
        // 开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<BasicInfo> basicInfos = infoMapper.selectResend(name,comPartyId);
        return PageInfo.of(basicInfos);
    }

    @Override
    public List<Client> getClient(String name,String comPartyId) {
        return infoMapper.getClient(name,comPartyId);
    }

    public Object pushDxm(BaseInfo baseInfo, String ak, String sk, String key) {
        try {
            CloseableHttpClient client = HttpClientUtils.createIgnoreCertClient();
            HttpPost httpPost = new HttpPost("https://dms.hun.hsip.gov.cn/isp-api/powercsb/110");

            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("_api_version", "1.0.0");
            long timestamp = Instant.now().toEpochMilli();
            httpPost.setHeader("_api_timestamp", String.valueOf(timestamp));
            httpPost.setHeader("_api_access_key", ak);
            System.out.println("ak=============>"+ak);
            System.out.println("sk==============>"+sk);
            httpPost.setHeader("Accept-Charset", "UTF-8");

            if ("1".equals(key)) {
                httpPost.setHeader("_api_name", "3563");
            } else {
                httpPost.setHeader("_api_name", "3562");
            }
            System.out.println("httpPost.getFirstHeader(\"_api_name\").getValue()=========>"+httpPost.getFirstHeader("_api_name").getValue());

            String sign = signCalc(httpPost.getFirstHeader("_api_name").getValue(), "1.0.0", ak, sk, String.valueOf(timestamp));
            httpPost.setHeader("_api_signature", sign);

            String dataJson = JSONObject.toJSONString(baseInfo);
            httpPost.setEntity(new StringEntity(dataJson, "UTF-8"));
            System.out.println("httpPost====>"+httpPost);
            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();

            Header contentType = entity.getContentType();
            System.out.println("返回的 Content-Type ===> " + contentType.getValue());
            String contentTypeValue = contentType.getValue();

            System.out.println("响应内容类型 Content-Type: " + contentType.getValue());
            if (contentTypeValue.contains("application/json")) {
                System.out.println(22222);
                // 是 JSON
                String entityStr = EntityUtils.toString(entity, "UTF-8");
                return JSON.parseObject(entityStr);
            } else {
                System.out.println(333333);
                // 是 Excel 文件（application/vnd.openxmlformats-officedocument.spreadsheetml.sheet）
                byte[] fileBytes = EntityUtils.toByteArray(entity);
                Map<String, Object> result = new HashMap<>();
                result.put("fileBytes", fileBytes);
                result.put("filename", "追溯下载_" + System.currentTimeMillis() + ".xlsx");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public String signCalc(String apiName,String apiVersion,String apiAccessKey,String apiEcreKey,String apiTimestamp) {
        String param = "_api_access_key="+ apiAccessKey +"&"+ "_api_name="+ apiName +"&"+"_api_timestamp="+ apiTimestamp +"&"+"_api_version=" +apiVersion;
        String sign = null;
        try {
            sign = hmacSha1Base64(apiEcreKey,param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    /**
     * 使用 HmacSHA1 加密字符串，并返回 Base64 编码结果
     * @param secret  密钥
     * @param message 待加密的字符串
     * @return Base64 编码的签名
     */
    public static String hmacSha1Base64(String secret, String message) throws Exception {
        // 1. 获取 HmacSHA1 算法的 Mac 实例
        Mac mac = Mac.getInstance("HmacSHA1");

        // 2. 将密钥转换为字节数组（UTF-8 编码）
        byte[] keyBytes = secret.getBytes("UTF-8");
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // 3. 初始化 Mac 实例
        mac.init(signingKey);

        // 4. 加密消息（UTF-8 编码）
        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));

        // 5. 将字节数组转换为 Base64 字符串
        return Base64.getEncoder().encodeToString(rawHmac);
    }
}
